/********************************************************************************
  DESCRIPTION OF THE FILE HERE
la porta viene creata dal server
********************************************************************************/

#include "mtserver.h"
#include "common.h"

#include "pool.h"
#include "port.h"
#include "request.h"
#include "response.h"

#define LOGGING_LAPSE 1*MICROSEC /* expressed in nanoseconds */
#define LOGGING_FILE_NAME "mtserver.log"

typedef struct SMTServer {  
  ptrPool pool; /* pool di thread  */
  /* thread realtivi ai client che restano in attesa finche' i compiti non sono svolti */
  ptrPort port; /* porta su cui vengono scritte le richieste */
} MTServer;

static void MTServer_init(ptrMTServer server, int pool_size){
  server->port = Port_create();
  server->pool = Pool_create(pool_size, LOGGING_LAPSE, LOGGING_FILE_NAME);
}

ptrMTServer MTServer_create(){
  ptrMTServer server = new(MTServer);
  MTServer_init(server, POOL_MIN_SIZE);
  return server;
}

void MTServer_listen(ptrMTServer server){
  if (server == NULL) throw_error("MTServer_listen", "null server");

  while (1){
    /* controlla se qualcuno ha avanzato una qualche richiesta e nel caso risolvila */
    Port_manageRequest(server->port, server->pool); /* supposta bloccante */    
  }
}

#ifdef DEBUG
void MTServer_printf (ptrMTServer server){
  /* BLA, BLA, BLA */
}
#endif /* DEBUG */

static void MTServer_deinit(ptrMTServer server){
  Pool_destroy(server->pool);
  Port_destroy(server->port);  
};

void MTServer_destroy(ptrMTServer server){
  if (server != NULL){
    MTServer_deinit(server);
    delete(server);
  }
}
